package graph.views;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JToolBar;

public class ToolbarPanel extends JPanel implements ActionListener {

	private IToolbarAction toolbarAction;;

	private String tools[][] = {
			{ "new.png", "new", "New a graph", "New" },
			{ "open.png", "open", "Open a graph file", "Next" },
			{ "save.png", "save", "Save this graph", "Save" },
			{ "switch.png", "switch", "Switch drawing/running mode", "Switch" },
			{ "clear.png", "clear", "clear this graph", "Clear" } };

	public ToolbarPanel() {
		super(new BorderLayout());

		JToolBar toolBar = new JToolBar("Graph Toolbar");
		toolBar.setFloatable(false);
		addButtons(toolBar);

		add(toolBar, BorderLayout.PAGE_START);
	}

	public void setToolbarAction(IToolbarAction toolbarAction) {
		this.toolbarAction = toolbarAction;
	}

	protected void addButtons(JToolBar toolBar) {
		JButton button = null;
		for (int i = 0; i < tools.length; i++) {
			button = makeNavigationButton(tools[i][0], tools[i][1],
					tools[i][2], tools[i][3]);
			toolBar.add(button);
		}
	}

	protected JButton makeNavigationButton(String imageName,
			String actionCommand, String toolTipText, String altText) {
		// Look for the image.
		String imgLocation = "images/" + imageName;
		URL imageURL = this.getClass().getResource(imgLocation);

		// Create and initialize the button.
		JButton button = new JButton();
		button.setActionCommand(actionCommand);
		button.setToolTipText(toolTipText);
		button.addActionListener(this);

		if (imageURL != null) { // image found
			button.setIcon(new ImageIcon(imageURL, altText));
		} else { // no image found
			button.setText(altText);
			System.err.println("Resource not found: " + imgLocation);
		}

		return button;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();
		// new command
		if (command == tools[0][1]) {
			toolbarAction.newAction();
		} else if (command == tools[1][1]) {
			toolbarAction.openAction();
		} else if (command == tools[2][1]) {
			toolbarAction.saveAction();
		} else if (command == tools[3][1]) {
			toolbarAction.swichAction();
		} else if (command == tools[4][1]) {
			toolbarAction.clearAciton();
		}
	}
}
